package com.buka.filter;

import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import netscape.javascript.JSObject;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import reactor.netty.http.server.HttpServerResponse;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Component
public class MyFilter implements GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拦截时间：
        LocalDateTime currentTime = LocalDateTime.now();
        int hour = currentTime.getHour();
        if(hour >= 14 && hour < 16){

            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.NOT_FOUND);//状态码改为404
            response.getHeaders().add("error", "时间段内不允许访问");
            response.getHeaders().add("content-type", "application/json;charset=utf-8");
            String error = "时间段内不允许访问";

//            JsonObject jsonObject = new JsonObject();
//            jsonObject.addProperty("error", error);
//            error = jsonObject.toString();

            DataBuffer wrap = response.bufferFactory().wrap(error.getBytes(StandardCharsets.UTF_8));
            Mono<Void> voidMono = response.writeWith(Mono.just(wrap));
            //拦截
            return voidMono;
        }else{
            //放行
            return chain.filter(exchange);
        }
    }
}
